<template>
  <div id="main" style="width: 500px;height:400px;"></div>
</template>

<script>
import * as echarts from 'echarts';
import {statisticsCategory} from '@/api/goods_manage/category'
export default {
  name:"商品分类统计柱状图",
  data() {
    return {
      //  category 分类柱状图数据
      data: [],
      //柱状图最上面的数据
      seriesData: [],
      myChart:null, // 存放echarts

    };
  },
  mounted() {
    this.myChart = echarts.init(document.getElementById('main'));
    this.loadDataAndDrawChart();
  },
  methods: {
    async loadDataAndDrawChart() {
      await this.statisticsCategory(); // 等待数据加载完成
      this.drawChart(); // 数据加载完成后执行绘制图表的操作
    },
    //获取统计数据
    async statisticsCategory() {
      try {
        // 需要进行 await
        const response = await statisticsCategory({});
        // console.log(response)
        //统计数据
        this.seriesData = response.data.data.map((item) => item.value);
        //分类数据
        this.data = response.data.categoryData;
      } catch (error) {
        console.error('Failed to load data:', error);
      }
    },
    //绘制数据
    drawChart() {
      let option;
      option = {
        xAxis: {
          type: 'category',
          data: this.data
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: this.seriesData,
            type: 'bar'
          }
        ]
      };
      this.myChart.setOption(option)
    },
  }
}
</script>

